package com.jiexin.schedule;

import com.jiexin.common.ConfigDatasource;
import com.jiexin.common.FileListener;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: Jay_Liu
 * @Description: 监听srcFilePath文件夹
 * @Trigger：
 * @Date: Created in 10:55 2018/8/22
 * @Modified By:
 */
@Component
@Slf4j
public class ParseXml implements CommandLineRunner {

    @Autowired
    private ConfigDatasource configDatasource;

    @Resource(name = "fileListener")
    private FileListener fileListener;

    @Override
    public void run(String... args) throws Exception {
        String srcFilePath = configDatasource.getConfig("srcFilePath");
        long interval = TimeUnit.SECONDS.toMillis(5L);
        new FileAlterationObserver(srcFilePath, FileFilterUtils.and(new IOFileFilter[]{FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter(".txt")}), (IOCase)null);
        FileAlterationObserver observer = new FileAlterationObserver(srcFilePath);
        observer.addListener(fileListener);
        FileAlterationMonitor monitor = new FileAlterationMonitor(interval, new FileAlterationObserver[]{observer});
        monitor.start();
        log.info("begin file monitoring:" + srcFilePath);
    }
}

